package com.ikaros.service.impl;

import com.ikaros.dto.OrderDTO;
import com.ikaros.enums.ResultEnums;
import com.ikaros.exception.SellException;
import com.ikaros.service.BuyerService;
import com.ikaros.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * Created by Ikaros on 2017/11/5.
 */
@Slf4j
@Service("buyerService")
public class BuyerServiceImpl implements BuyerService{
    private OrderService orderService;
    @Override
    public OrderDTO findOrderOne(String orderId, String openid) {
        return checkOrderOwner(orderId, openid);
    }

    @Override
    public OrderDTO cancelOrder(String orderId, String openid) {
        OrderDTO orderDTO = checkOrderOwner(orderId, openid);
        if (orderDTO==null){
            log.error("【取消订单】查不到该订单 orderId={}",orderId);
            throw new SellException(ResultEnums.ORDER_NOT_EXIST);
        }
        return orderService.cancel(orderDTO);
    }

    private OrderDTO checkOrderOwner(String orderId, String openid){
        OrderDTO orderDTO = orderService.findOne(orderId);
        if (orderDTO==null){
            return null;
        }
        //判断订单是否属于自己
        if (!orderDTO.getBuyerOpenid().equals(openid)){
            log.error("【取消订单】订单的openid不一致. openid={},orderDTO={}",openid,orderDTO);
            throw new SellException(ResultEnums.ORDER_MASTER_ERROR);
        }
        return orderDTO;
    }
}
